package com.sunline.gateway.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @Author: DougLiang
 * @CreateTime: 2024-06-04
 * @Description: DES加解密工具类
 * @Version: 1.0
 */

public class DESUtil {

    // DES密钥算法
    private static final String KEY_ALGORITHM = "DES";

    // 可选的有56, 112, 168，这里使用56，因为DES常用的就是56位
    private static final int KEY_SIZE = 56;

    // 生成密钥
    public static SecretKeySpec generateDESKey() throws Exception {

        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        keyGenerator.init(KEY_SIZE, new SecureRandom());
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] keyBytes = secretKey.getEncoded();

        // 转换密钥
        return new SecretKeySpec(keyBytes, KEY_ALGORITHM);
    }

    // DES加密
    public static String encryptDES(String data,SecretKeySpec key) throws Exception {
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] cipherText = cipher.doFinal(data.getBytes());

        // 编码并输出
        return Base64.getEncoder().encodeToString(cipherText);
    }

    // DES解密
    public static String decryptDES(String data,SecretKeySpec key) throws Exception {
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedTextBytes = cipher.doFinal(Base64.getDecoder().decode(data));
        return new String(decryptedTextBytes);
    }

    public static void main(String[] args) throws Exception {

        String text = "Hello World!";
        SecretKeySpec key = generateDESKey();
        String encryptedText = encryptDES(text,key);
        String decryptedText = decryptDES(encryptedText,key);

        System.out.println("Original Text: " + text);
        System.out.println("Encrypted Text: " + encryptedText);
        System.out.println("Decrypted Text: " + decryptedText);

    }



}
